package com.example.demo.page.demo

import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.example.demo.application.MyApplication
import com.example.demo.base.BaseViewModel
import com.example.demo.dao.UserDao
import kotlinx.coroutines.launch
import timber.log.Timber

//测试界面 viewModel
class DemoViewModel : BaseViewModel<DemoAction, DemoState, DemoEvent>() {
    private val userDao: UserDao = MyApplication.instance.database.userDao()

    private val demoRepository: DemoRepository by lazy {
        DemoRepository(userDao)
    }

    /**
     * 处理action
     */
    override fun onAction(action: DemoAction, state: DemoState?) {
        when (action) {
            is DemoAction.ClickLogin -> login(action.name, action.pwd)
            DemoAction.Navigation -> {
                Timber.d("点击了跳转按钮")
//                emitEffect { DemoEvent.NavigationToHost }
            }
        }
    }

    /**
     * 模拟登陆
     */
    private fun login(name: String, pwd: String) {
        emitState { DemoState.Loading }
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
            emitState { DemoState.Error("账号或密码不能为空") }
            return
        }
        Timber.d("开始请求")
        viewModelScope.launch {
            var isLoginSuccess: Boolean
            demoRepository.login(name, pwd).also { isLoginSuccess = it }
            Timber.d("isLoginSuccess=$isLoginSuccess")
            if (isLoginSuccess) {
                emitState { DemoState.LoginSuccess }
            } else {
                emitState { DemoState.Error("账号或密码错误") }
            }
        }

    }


}